<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="/common/template :: header(~{::title},~{::link},~{::style})">
</head>
<style>
    .shoplabel {
        width: 20%;
    }
    ::-webkit-scrollbar-thumb{
        background-color: #009688;
    }
    #imgdiv {
        width: 240px;
        height: 150px;
        border: 2px dashed #000;
    }


    #btnItem{
        text-align: center;
        background-color: white;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        margin: 0 0 0;
        padding: 15px 0 15px 0;
    }
</style>
<body>
<div class="layui-form timo-compile">
    <form onsubmit="return false" style="height: 100%;width: 90%;margin-left: 10%;margin-bottom: 34px;">
        <input type="hidden" name="shopId" th:if="${shops}" th:value="${shops.shopId}">
        <div class="layui-form-item">
            <label class="layui-form-label shoplabel"><span style="color: red">* </span>店铺名称：</label>
            <div class="layui-input-inline">
                <input class="layui-input" type="text" name="shopName" placeholder="请输入店铺名称"
                       th:value="${shops?.shopName}">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label shoplabel"> 店长：</label>
            <div class="layui-input-inline">
                <input name="userId" hidden>
                <input class="layui-input" type="text" id="storeManager" placeholder="点击获取店长" readonly="readonly">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label shoplabel"><span style="color: red">* </span>位置：</label>
            <input name="areaId" th:value="${shops?.areaId}" hidden>
            <div class="layui-input-inline">
                <cascader id="demo1"></cascader>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label shoplabel"><span style="color: red">* </span>详细地址：</label>
            <div class="layui-input-inline">
                <input class="layui-input" type="text" name="address" placeholder="请输入地址" th:value="${shops?.address}">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label shoplabel"><span style="color: red">* </span>联系人：</label>
            <div class="layui-input-inline">
                <input class="layui-input" type="text" name="contactsName" placeholder="请输入联系人名称"
                       th:value="${shops?.contactsName}">
            </div>
        </div>


        <div class="layui-form-item">
            <label class="layui-form-label shoplabel"><span style="color: red">* </span>电话：</label>
            <div class="layui-input-inline">
                <input class="layui-input" type="text" name="phone" placeholder="请输入电话" th:value="${shops?.phone}">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label shoplabel">备用电话：</label>
            <div class="layui-input-inline">
                <input class="layui-input" type="text" name="sparePhone" placeholder="请输入备用电话"
                       th:value="${shops?.sparePhone}">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label shoplabel">经度：</label>
            <div class="layui-input-inline">
                <input class="layui-input" type="text" name="longitude" placeholder="请输入经度"
                       th:value="${shops?.longitude}">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label shoplabel">纬度：</label>
            <div class="layui-input-inline">
                <input class="layui-input" type="text" name="latitude" placeholder="请输入纬度"
                       th:value="${shops?.latitude}">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label shoplabel"><span style="color: red">* </span>营业状态：</label>
            <div class="layui-input-inline">
                <select name="openingStatus" lay-verify="openingStatus">
                    <option value=""></option>
                    <option value="0">营业中</option>
                    <option value="1">休息中</option>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label shoplabel"><span style="color: red">* </span>服务类型：</label>
            <div class="layui-input-inline">
                <div id="shopType"  name="shopType" class="xm-select-demo"></div>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label shoplabel">图片上传：
                <br/>
                <span style="font-size: 12px;color: darkorchid">大小不能超过1m</span><br>
                <span style="font-size: 12px;color: darkorchid">高不大于600px</span><br>
                <span style="font-size: 12px;color: darkorchid">宽不超过800px</span>
            </label>
            <div class="layui-input-inline">
                <input id="fileUpload" type="file" style="display:none" name="file" accept="image/*"/>
                <div id="imgdiv">
                    <img class="img" style="width: 240px;height: 150px"/>
                </div>
            </div>
            <div style="height: 200px">
                <br/>
                <button id="uploads" class="layui-btn layui-btn-sm layui-btn-radius layui-btn-normal" type="button">上传
                </button>
                <br/>
                <br/>
                <button id="removes" class="layui-btn layui-btn-sm layui-btn-radius layui-btn-normal" type="button">移除
                </button>
                <br/>
                <br/>
                <button id="preview" class="layui-btn layui-btn-sm layui-btn-radius layui-btn-normal" type="button">预览
                </button>
            </div>
        </div>
        <div class="layui-form-item timo-finally" id="btnItem" style="height: 6%">
            <button class="layui-btn" id="submit"><i class="fa fa-check-circle"></i> 保存</button>
            <button class="layui-btn btn-secondary close-popup"><i class="fa fa-times-circle"></i> 关闭</button>
        </div>
    </form>
</div>
<script th:replace="/common/template :: script"></script>
<script type="text/javascript" src="/lib/layui-v2.5.7/mods/xm-select.js"></script>

<!--选择店长弹窗-->
<!-- 选择店长弹窗操作列 -->
<script type="text/html" id="userTableBar">
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="addShopUser">添加到店铺人员</a>
</script>
<!--选择店长弹窗实体部分-->
<script type="text/html" id="selectUser">
    <div class="layui-row timo-card-screen">
        <div class="pull-left layui-form-pane timo-search-box">
            <div class="layui-inline">
                <label class="layui-form-label shoplabel">手机号：</label>
                <div class="layui-input-block">
                    <input type="text" name="managerPhone" placeholder="请输入您要添加的手机号码" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <button class="layui-btn " id="userBtn">
                    <i class="fa fa-search"></i>
                </button>
            </div>
        </div>
    </div>
    <div>
        <table class="layui-table" id="userTable" lay-filter="userTable"></table>
    </div>
    <div>
        <button></button>
    </div>
</script>
<script th:inline="javascript">
    layui.config({
        base: '/lib/layui-v2.5.7/mods/ajaxCascader/'
        /*, version: '1.6'*/
    });
    layui.use(['jquery', 'ajaxCascader', 'laydate','layer','table','form'], function () {
        var $ = layui.jquery;
        var laydate = layui.laydate;
        var cascader = layui.ajaxCascader;
        var layer = layui.layer;
        var table = layui.table;
        var form = layui.form;
        //var select = layui.xm-select;
        var areaId = $("input[name='areaId']").val();
        //form.render('select');
        //打开添加就全屏
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.full(index);

        var select = xmSelect.render({
            el: '#shopType',
            style: {
                width: '100%',
                height: '38px',
            }
        })

        $.ajax({
            url: '/shopsService/shops/getShopType',
            type: 'get',
            async : false,
            success: function (res) {
                select.update({
                    data: res.data
                })

            }
        })



        // Ajax传参模式
        cascader.load({
            elem: '#demo1'
            , height: 38
            , width: 240
            , search: {
                show: true,
                minLabel: 5,
                placeholder: '点击选择位置'
            }
            , clear: true
            , showlast: true
            , value: 0
            , getChildren: function (value, callback) {
                var data = []
                $.ajax({
                    url: '/shopsService/shops/getAreaData/' + value,
                    type: 'get',
                    success: function (res) {
                        data = res.data;
                        for (var i in data) {
                            data[i].value = data[i].id;
                            data[i].label = data[i].name;
                            delete data[i].id;
                            delete data[i].name;
                            if (data[i].level == 2) {
                                data[i].hasChild = false;
                            } else {
                                data[i].hasChild = true;
                            }

                        }
                        callback(data);
                    }
                });
            },
        });

        //位置参数不为空时执行，（顺便执行一些复写）
        if(areaId){
            $.ajax({
                url: '/shopsService/shops/getMyAreaData/' + areaId,
                type: 'get',
                async : false,
                success: function (res) {

                    $("input[class='layui-input cascader-input']").val( res.data[0].wholeName.replace(/，/g,""))
                }
            })
            //获取店长
            $.ajax({
                url: '/shopsService/shops/getManager/'+$("input[name='shopId']").val(),
                type: 'get',
                async : false,
                success: function (res) {
                    $("input[name='userId']").val(res.data.id);
                    $("#storeManager").val(res.data.phone?(res.data.nickName?res.data.nickName:res.data.phone+'(该用户暂无名称)'):'(暂无店长)')
                }
            })
            var openingStatus = [[${shops?.openingStatus}]];
            $("select[name='openingStatus']").val(openingStatus);
            var openingStatus = [[${shops?.openingStatus}]];
            $("select[name='openingStatus']").val(openingStatus);
            form.render('select');
            var shopType = [[${shops?.shopType}]]
            var shopTypes =  shopType.split(',');
            select.setValue(shopTypes);
            var imgSrc = [[${shops?.shopPicture}]]
            $(".img").attr("src", imgSrc);
        }

        //选择店长
        $("#storeManager").click(function () {
            layer.open({
                type: 1,
                title: '选择店长',
                area: ['80%','50%'],
                content: $('#selectUser').html(),
                success : function (layero, index)  {
                    //初始化表格
                    var userTable = table.render({
                        elem: '#userTable',
                        data: [],
                        cellMinWidth: 100,
                        cols: [
                            [
                                {field: 'username', title: '账号名称', align: "center"},
                                {field: 'nickname', title: '真实名称', align: "center"},
                                {field: 'sex', title: '性别', align: "center", templet: function (d) {
                                        if(d.sex==1){
                                            return "男";
                                        }else {
                                            return "女";
                                        }
                                    }
                                },
                                {field: 'phone', title: '手机号码', align: "center"},
                                {align: 'center', toolbar: '#userTableBar', title: '操作'}
                            ]
                        ]
                    });

                    $("#userBtn").click(function () {
                        var phone = $("input[name='managerPhone']").val();
                        if(phone){
                            $.ajax({
                                url: '/shopsService/shops/searchUser?phone=' + phone,
                                method: 'get',
                                // data: {"access_token": tokens},
                                success: function (res) {
                                    if(res.data[0]){
                                        userTable.reload({
                                            data : res.data,
                                            limit : res.count
                                        })
                                    }else {
                                        layer.msg("未查询到该手机号")
                                    }
                                }
                            })
                        }else {
                            layer.msg("请填写手机号")
                        }
                    })

                    // 工具条点击事件
                    table.on('tool(userTable)', function (obj) {
                        var data = obj.data;
                        var layEvent = obj.event;
                        if (layEvent === 'addShopUser') { //
                            $("#storeManager").val(data.nickname)
                            $("input[name='userId']").val(data.id)
                            layer.close(index);
                        }
                    });
                }
            })
        })

        //提交事件
        $("#submit").click(function () {
            var inputData = $('form').serializeArray();
            var formData = new FormData();
            for (var f in inputData) {
                formData.append(inputData[f].name, inputData[f].value);
            }
            formData.append("shopType",select.getValue('value'))
            formData.append("shopTypeName",select.getValue('nameStr'))
            //将图片添加到fromdata
            // var flag = false;
            $('#fileUpload').each(function () {
                var files = $(this)[0].files[0];
                if (files == null ) {
                    var imgSrc = $(".img").attr("src");
                    if(imgSrc){
                        formData.append("shopPicture", imgSrc);
                        // flag = true;
                    }else {
                        // layer.msg("图片未添加", {icon: 2});
                    }
                } else {
                    formData.append($(this).attr('name'), $(this)[0].files[0]);
                    // flag = true;
                }
            });
            //图片不为空才能提交if(flag){}
                $.ajax({
                    url: "/shopsService/shops/save",
                    data: formData,
                    type: "Post",
                    //cache: false,上传文件无需缓存
                    processData: false,//用于对data参数进行序列化处理 这里必须false
                    contentType: false, //必须
                    success: function (data) {
                        if(data.code==200){
                            layer.msg(data.msg);
                            parent.window.location.href="/shopsService/shops/index?msg="+data.msg;
                        }else {
                            layer.msg(data.msg,{time:1500});
                        }
                    }
                })


        })


/*        //时间范围
        laydate.render({
            elem: '#openingHours'
            ,type: 'time'
            ,range: '-'
            , format: 'HH:mm'
        });*/

        //上传图片
        $('#uploads').click(function () {
            $(".img").show();
            return $('#fileUpload').click(); //注意这句，主要是需要return点击事件返回值
        });
        //移除图片
        $('#removes').click(function () {
            //清空文件上传
            var file = document.getElementById('fileUpload');
            if (file.value) {
                file.value = '';
            } else {
                layer.msg("无图片")
                return
            }
            $(".img").removeAttr("src");
            $(".img").hide();
        });

        //选择图片后回显img
        $('#fileUpload').change(function () {
            $(".img").attr("src", URL.createObjectURL($(this)[0].files[0]));
        });

        //图片验证
        $("#fileUpload").change(function () {
            var fileTypes = [".jpg", ".png"];  //我们所需要的图片格式
            var filePath = this.value;
            if (filePath) {
                var filePic = this.files[0];            //选择的文件内容--图片
                var fileType = filePath.slice(filePath.indexOf("."));   //选择文件的格式
                var fileSize = this.files[0].size;            //选择文件的大
                if (fileTypes.indexOf(fileType) == -1) {  //判断文件格式是否符合要求
                    $('#removes').click();
                    layer.msg("文件格式不符合要求！");
                    return
                }
                if (fileSize > 1024 * 1024) {
                    $('#removes').click();
                    layer.msg("文件大小不能超过1M！");
                    return
                }
                var reader = new FileReader();
                reader.readAsDataURL(filePic);
                reader.onload = function (e) {
                    var data = e.target.result;
                    //加载图片获取图片真实宽度和高度
                    var image = new Image();
                    image.onload = function () {
                        var width = image.width;
                        var height = image.height;
                        if (width <= 800 && height <= 600) {  //判断文件像素
                            //上传图片
                        } else {
                            $('#removes').click();
                            layer.msg("图片大小有问题");
                            return;
                        }
                    };
                    image.src = data;
                };
            } else {
                return
            }

        })

        $('#preview').click(function () {
            var interimPath = $(".img").attr("src");
            if (interimPath) {
                previewImg(interimPath);
            } else {
                layer.msg("请添加图片来浏览")
            }
        });


        // 选择器点击事件的监听
        cascader.on('click', '#demo1', function () {
            // 获取位置参数数组
            var areaIds = cascader.getChooseData('#demo1')
            $("input[name='areaId']").val(areaIds.length==0?'':areaIds[areaIds.length-1]);
        });


        //预览图片点击事件
        function previewImg(carouselPath) {
            layer.photos({
                photos: {"data": [{"src": carouselPath}]}
                , anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
            });
        }
    })
</script>
</body>
</html>
